﻿using Timeline.Beans;
using Timeline.Inis;
using Timeline.Utils;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading;
using Windows.Storage;
using System.Linq;
using Windows.ApplicationModel.Resources;

namespace Timeline.Providers {
    public class LocalProvider : GeneralProvider {
        private Meta ParseBean(StorageFile file) {
            string imgId = TextUtil.Md5(file.Path);

            Meta meta = new Meta {
                Id = imgId,
                Uhd = file.Path,
                Thumb = file.Path,
                Story = file.Name,
                Date = file.DateCreated.DateTime,
                IdGlobalPrefix = this.Id,
                IdGlobalSuffix = imgId,
                Format = ".".Equals(file.FileType) ? ".jpg" : file.FileType,
            };

            //BasicProperties properties = await file.GetBasicPropertiesAsync();
            //meta.Date = properties.ItemDate.DateTime;
            return meta;
        }

        private void FixBean(string titleRule, string captionRule, string order) {
            //string folderName = (await file.GetParentAsync()).Name;
            //string folderName = folder.Name.Length > 16 ? folder.Name.Substring(0, 16) + "..." : folder.Name;
            for (int i = 0; i < metas.Count; ++i) {
                Meta meta = this.metas[i];
                meta.No = metas.Count - i;
                //meta.Title = string.Format("~\\{0} #{1}", folderName, metas[i].No);
                if (!string.IsNullOrEmpty(titleRule)) {
                    meta.Title = titleRule.Replace("{title}", "")
                        .Replace("{order}", order)
                        .Replace("{no}", meta.No.ToString());
                } else {
                    meta.Title = "";
                }
                if (!string.IsNullOrEmpty(captionRule)) {
                    meta.Caption = captionRule.Replace("{title}", "")
                        .Replace("{order}", order)
                        .Replace("{no}", meta.No.ToString());
                } else {
                    meta.Caption = "";
                }
            }
        }

        public override async Task<bool> LoadData(CancellationToken token, Ini ai, GeneralIni gi, Go go) {
            LocalIni ini = gi as LocalIni;
            StorageFolder folder = await FileUtil.GetGalleryFolder(ai.Folder);
            if (folder == null) {
                return false;
            }
            LogUtil.D("LoadData() provider folder: " + folder.Path);
            try {
                // CommonFileQuery.OrderByDate 只能对库中的文件夹或家庭组文件夹中使用此选项（库外文件夹将导致异常）；深层简单列表
                // CommonFileQuery.DefaultQuery 此选项用于任何存储位置；浅表列表
                IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();
                if ("date".Equals(gi.Order)) {
                    files = files.OrderByDescending(f => f.DateCreated.DateTime).ToList();
                } else { // random
                    Random random = new Random(go.Seed);
                    files = files.OrderBy(f => random.NextDouble()).ToList();
                }
                if (go.CheckFilterEndDate()) {
                    DateTime filterEndDate = go.FilterEndDate.Date.AddDays(1); // 次日零点为临界点
                    files = files.Where(x => x.DateCreated.DateTime < filterEndDate).ToList();
                }
                LogUtil.D("LoadData() provider inventory: " + files.Count);
                List<string> loadedNames = new List<string>();
                foreach (Meta meta in this.metas) {
                    loadedNames.Add(meta.Story);
                }
                List<Meta> metasAdd = new List<Meta>();
                foreach (StorageFile file in files) {
                    if (file.ContentType.StartsWith("image") && !loadedNames.Contains(file.Name)) {
                        metasAdd.Add(ParseBean(file));
                    }
                }
                if (metasAdd.Count > 0) {
                    AppendMetas(metasAdd);
                    string order = ResourceLoader.GetForCurrentView().GetString("Order_" + gi.Order);
                    FixBean(gi.TitleRule, gi.CaptionRule, order);
                }
                return true;
            } catch (Exception e) {
                LogUtil.E("LoadData() " + e.Message);
            }
            return false;
        }
    }
}
